package services

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"vala/tools"
)

type MysqlService struct {
	Dir          string
	ExecFile     string
	Process      *os.Process
	ProcessState chan *os.ProcessState
}

func NewMysqlService(dir string, execFile string) *MysqlService {
	return &MysqlService{
		Dir:          dir,
		ExecFile:     execFile,
		ProcessState: make(chan *os.ProcessState),
	}
}

func (mysqlService *MysqlService) Start() {
	mysqlService.Process, mysqlService.ProcessState = tools.StartProcess(
		mysqlService.ExecFile,
		[]string{"--pid-file", filepath.Join(mysqlService.Dir, "data", "my.pid")},
	)
}

func (mysqlService *MysqlService) Stop() {
	mysqlService.Process.Kill()
	<-mysqlService.ProcessState
}

func (mysqlService *MysqlService) Reload() {
	mysqlService.Stop()
	mysqlService.Start()
}

// 目前仍然以Pid文件是否存在来判断
func (mysqlService *MysqlService) Status() bool {
	var pidFile = filepath.Join(mysqlService.Dir, "data", "my.pid")
	if tools.IsExist(pidFile) {
		pidByt, error := ioutil.ReadFile(pidFile)
		if error != nil {
			return false
		}
		// 获取PID
		pid, error := strconv.Atoi(strings.TrimRight(strings.TrimRight(string(pidByt), "\n"), "\r"))
		if error != nil {
			panic(error)
		}
		_, error = os.FindProcess(pid)
		if error != nil {
			return false
		}

		return true
	}

	return false
}
